package com.nodecollege.cloud.client.interceptor;

import com.nodecollege.cloud.common.UpmsConstants;
import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.model.LoginUser;
import com.nodecollege.cloud.common.utils.ThreadUserUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author LC
 * @date 2020/1/10 9:55
 */
@Slf4j
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {

    @Value("${spring.application.name:default}")
    private String applicationName;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header(NCConstants.NC_REQUEST_ID, MDC.get(NCConstants.REQUEST_ID));
        requestTemplate.header(NCConstants.NC_THREAD_ID, MDC.get(NCConstants.THREAD_ID));
        requestTemplate.header(UpmsConstants.HEADER_ACCESS_SOURCE, applicationName);
        LoginUser loginUser = ThreadUserUtils.getLoginUser();
        if (loginUser != null) {
            requestTemplate.header(UpmsConstants.HEADER_ACCESS_TOKEN, loginUser.getAccessToken());
            requestTemplate.header(UpmsConstants.HEADER_INFO_RANDOM, loginUser.getInfoRandom());
        }
    }
}
